#!/bin/bash

# Flutter项目测试结果汇总脚本
# 分析最近的测试日志并生成汇总报告

set -e

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$PROJECT_ROOT"

echo -e "${BLUE}📊 测试结果汇总分析${NC}"
echo "=================================="

# 检查日志目录
LOG_DIR="$PROJECT_ROOT/logs"
if [ ! -d "$LOG_DIR" ]; then
    echo -e "${YELLOW}⚠️  没有找到日志目录${NC}"
    exit 0
fi

# 获取最新的日志文件
LATEST_LOG=$(find "$LOG_DIR" -name "test_*.log" -type f -exec ls -t {} + | head -n 1)

if [ -z "$LATEST_LOG" ]; then
    echo -e "${YELLOW}⚠️  没有找到测试日志文件${NC}"
    exit 0
fi

echo -e "${BLUE}📄 分析日志文件: $(basename "$LATEST_LOG")${NC}"
echo

# 统计信息
TOTAL_LINES=$(wc -l < "$LATEST_LOG")
SUCCESS_COUNT=$(grep -c "\[SUCCESS\]" "$LATEST_LOG" || echo "0")
WARNING_COUNT=$(grep -c "\[WARNING\]" "$LATEST_LOG" || echo "0")
ERROR_COUNT=$(grep -c "\[ERROR\]" "$LATEST_LOG" 2>/dev/null || echo "0")
INFO_COUNT=$(grep -c "\[INFO\]" "$LATEST_LOG" || echo "0")

echo -e "${BLUE}📈 统计信息:${NC}"
echo "  总日志条数: $TOTAL_LINES"
echo -e "  成功: ${GREEN}$SUCCESS_COUNT${NC}"
echo -e "  警告: ${YELLOW}$WARNING_COUNT${NC}"
echo -e "  错误: ${RED}$ERROR_COUNT${NC}"
echo "  信息: $INFO_COUNT"
echo

# 显示警告和错误
if [ "$WARNING_COUNT" -gt 0 ]; then
    echo -e "${YELLOW}⚠️  警告信息:${NC}"
    grep "\[WARNING\]" "$LATEST_LOG" | tail -5
    echo
fi

if [ "$ERROR_COUNT" -gt 0 ]; then
    echo -e "${RED}❌ 错误信息:${NC}"
    grep "\[ERROR\]" "$LATEST_LOG" | tail -5
    echo
fi

# 测试执行时间分析
if grep -q "总耗时" "$LATEST_LOG"; then
    EXECUTION_TIME=$(grep "总耗时" "$LATEST_LOG" | tail -1 | sed 's/.*总耗时: //')
    echo -e "${BLUE}⏱️  执行时间: $EXECUTION_TIME${NC}"
fi

# 生成趋势分析（如果有多个日志文件）
LOG_COUNT=$(find "$LOG_DIR" -name "test_*.log" -type f | wc -l)
if [ "$LOG_COUNT" -gt 1 ]; then
    echo
    echo -e "${BLUE}📊 最近5次测试趋势:${NC}"
    find "$LOG_DIR" -name "test_*.log" -type f -exec ls -t {} + | head -5 | while read -r log_file; do
        log_date=$(basename "$log_file" | sed 's/test_\([0-9]*_[0-9]*\)\.log/\1/' | sed 's/_/ /')
        success_cnt=$(grep -c "\[SUCCESS\]" "$log_file" || echo "0")
        error_cnt=$(grep -c "\[ERROR\]" "$log_file" || echo "0")
        
        if [ "$error_cnt" -eq 0 ]; then
            status="${GREEN}✅${NC}"
        else
            status="${RED}❌${NC}"
        fi
        
        echo "  $log_date - $status (成功:$success_cnt, 错误:$error_cnt)"
    done
fi

echo
echo -e "${GREEN}✨ 汇总完成${NC}"

# 清理旧日志文件（保留最近10个）
LOG_FILES_COUNT=$(find "$LOG_DIR" -name "test_*.log" -type f | wc -l)
if [ "$LOG_FILES_COUNT" -gt 10 ]; then
    echo -e "${YELLOW}🧹 清理旧日志文件...${NC}"
    find "$LOG_DIR" -name "test_*.log" -type f -exec ls -t {} + | tail -n +11 | xargs rm -f
    echo "已清理 $((LOG_FILES_COUNT - 10)) 个旧日志文件"
fi
